<template>
  <!-- 页面-应用管理 -->
  <div class="ApplicationList-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form :model="formSearch" ref="roleFormSearch" slot="adaption-bar" class="ivu-form-no-margin-bottom" inline>
        <template>
          <!-- 应用编码 -->
          <Form-item prop="clientId" :label="$t('module.appManage.appCode')">
            <Input
              type="text"
              v-model.trim="formSearch.clientId"
              :maxlength="30"
              :placeholder="$t('module.appManage.enterclientId')"
              @on-enter="search"
            />
          </Form-item>

          <!-- 应用名称 -->
          <Form-item prop="appName" :label="$t('module.appManage.appNameGuess')">
            <Input
              type="text"
              v-model.trim="formSearch.appName"
              :maxlength="30"
              :placeholder="$t('module.appManage.enterappName')"
              @on-enter="search"
            />
          </Form-item>
          <!-- 所属租户 -->
          <Form-item prop="tenantCode" :label="$t('module.appManage.tenantCode')">
            <Select
              v-model="formSearch.tenantCode"
              style="width: 100%;"
              :placeholder="$t('module.appManage.entertenantCode')"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in searchTenantList"
                :value="item.vsiKey"
                :key="item.vsiKey"
                :label="item.vsiValue"
              ></Option>
            </Select>
          </Form-item>
          <!-- 状态 -->
          <Form-item prop="enabled" :label="$t('common.status')">
            <Select
              v-model="formSearch.enabled"
              style="width: 100%;"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="formReset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="appTable" :config="tableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="formReset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="edit()" />
      </div>
      <Form
      v-if="useTableSearchBar"
      :model="formSearch"
      ref="roleFormSearch"
      slot="table-search-bar"
      class="ivu-form-no-margin-bottom" inline>
        <template>
          <!-- 所属租户 -->
          <Form-item prop="tenantCode">
            <Select
              v-model="formSearch.tenantCode"
              style="width: 100%;"
              :placeholder="$t('module.appManage.entertenantCode')"
              filterable
              transfer
              @on-change="search(1)"
              clearable
            >
              <Option
                v-for="item in searchTenantList"
                :value="item.vsiKey"
                :key="item.vsiKey"
                :label="item.vsiValue"
              ></Option>
            </Select>
          </Form-item>
          <!-- 状态 -->
          <Form-item prop="enabled">
            <Select
              v-model="formSearch.enabled"
              style="width: 140px;"
              :placeholder="$t('common.warning.selectStatus')"
              @on-change="search(1)"
              clearable
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <Form-item prop="searchType">
            <Input
              type="text"
              v-model.trim="formSearch.searchTypeValue"
              :placeholder="searchTypePlaceholder"
              @on-enter="search"
              @on-blur="search"
            >
            <template #prepend>
              <Select v-model="formSearch.searchType" style="width: 110px" @on-change="searchTypeChange">
                <Option v-for="item in searchTypeList" :value="item.key" :key="item.key">{{
                item.name
              }}</Option>
              </Select>
            </template>
            </Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import { getAppList, deletApp, getTenantList } from "@/api/applicationApi.js";
import userCenter from "@/api/user.center.mixin";
import locales from "./locales.js";
import ApplicationEdit from "./AppEdit.vue";
import AppSetting from "./AppSetting.vue";
import appConfig from "./appConfig.vue"
import { CoreModuleName } from "@/const.js";
import tenantAPI from "@/api/tenantApi.js";
// import valueSetAPI from "@/api/valueSetAPI.js";
const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
export default {
  name: "application-list",
  mixins: [userCenter, locales],
  data() {
    const { userInfo } = $store.state[CoreModuleName];
    return {
      useTableSearchBar: false,
      userRepositorys: {},
      editIconLoading: false,
      currTenantCode: userInfo.tenantCode || "", //租户编码
      currTenantName: "", //租户名称
      searchTenantList: [], //所属租户下拉框数据
      searchStatusList: [], //状态下拉框数据
      formSearch: {
        clientId: "",
        appName: "",
        tenantCode: "ALL", //所属租户
        enabled: "ALL", //状态
        searchType: 'clientId',
        searchTypeValue: '',
      },
      searchTypeList: [
        {key: 'clientId',  name: this.$t('module.appManage.appCode'), placeholder: this.$t('module.appManage.enterclientId')},
        {key: 'appName',  name: this.$t('module.appManage.appNameGuess'), placeholder: this.$t('module.appManage.enterappName')},
      ],
      searchTypePlaceholder: this.$t('module.appManage.enterclientId'),
      // category: 0
    };
  },
  // data: () => ({
  //   userRepositorys: {},
  //   editIconLoading: false,
  //   searchTenantList: [], //所属租户下拉框数据
  //   searchStatusList: [], //状态下拉框数据
  //   formSearch: {
  //     clientId: "",
  //     appName: "",
  //     tenantCode: "ALL", //所属租户
  //     enabled: "ALL" //状态
  //   }
  // }),
  computed: {
    tableConfig() {
      return { loadDataFn: getAppList, columnsFn: this.generateColumns };
    }
  },
  created() {
    // const { userInfo } = $store.state[CoreModuleName];
    // this.category = userInfo.category;
    this.initData();
    this.getselectorList();
    this.searchStatusList = [
      {
        vsiKey: "0",
        vsiValue: this.$t("common.disable")
      },
      {
        vsiKey: "1",
        vsiValue: this.$t("common.enable")
      }
    ];
    // //   userCenter mixins
    // this.getUserCenterListData();
    this.initTenant(); //获取租户编码对应的租户名称
  },
  methods: {
    searchTypeChange() {
      if (this.formSearch.searchTypeValue) {
        this.search()
      }
    },
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant() {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (this.currTenantCode == tenant.tenantCode) {
            this.currTenantName = tenant.tenantName;
          }
        }
      });
    },
    // //初始化所有 所属租户、状态（选择器列表）
    // async getselectorList() {
    //   const [searchTenantList, searchStatusList] = await Promise.all([
    //     getTenantList(),
    //     valueSetAPI.getValueSetByCode("ENABLED_CODE")
    //   ]);
    //   this.searchTenantList = searchTenantList.data;
    //   this.searchStatusList = searchStatusList;
    // },
    //初始化所有 所属租户（选择器列表）
    getselectorList() {
      getTenantList().then(res => {
        this.searchTenantList = res.data.map(item => {
          return {
            vsiKey: item.vsiKey,
            vsiValue: item.vsiValue
          };
        });
      });
    },
    generateColumns() {
      return [
        {
          title: `${this.$t("module.appManage.appCode")}`,
          key: "clientId",
          sortable: "custom"
        },
        {
          title: this.$t("module.appManage.appName"),
          key: "appName",
          sortable: "custom"
        },
        {
          title: this.$t("module.appManage.domainName"),
          key: "domainName"
        },
        {
          title: this.$t("module.appManage.tenant"),
          align: "left",
          key: "tenantName"
        },
        // {
        //   title: this.$t("module.appManage.userCenter"),
        //   key: "userRepository",
        //   render: (h, params) => {
        //     return h("span", {}, this.getUserCenterName(params.row.userRepository));
        //   }
        // },
        {
          title: this.$t("module.appManage.clientSecretPlaintext"),
          key: "clientSecretPlaintext",
          width: 275
        },
        {
          title: this.$t("common.status"),
          align: "center",
          key: "enabled",
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              "StatusButton",
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },
                props: {
                  status: params.row.enabled == 1 ? "0" : "1"
                }
              },
              params.row.enabled == 1 ? this.$t("common.enable") : this.$t("common.disable")
            );
          }
        },
        {
          title: this.$t("common.operating"),
          align: "left",
          fixed: "right",
          width: 110,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: this.getOperatingCols(params.row)
              }
            });
          }
        }
      ];
    },
    getOperatingCols(row) {
      let operatingCols = [];
      // let tenants = this.$store.state[CoreModuleName].userInfo.tenantCode;
      if (this.currTenantCode == row.tenantCode || row.tenantCode == "") {
        operatingCols.push({
          type: "icon",
          icon: "md-create",
          text: this.$t("common.edit"),
          // hidden: this.category != 1,
          handle: () => {
            this.edit(row.id,row);
          }
        });
        operatingCols.push({
          type: "icon",
          icon: "ios-settings",
          text: this.$t("module.appManage.appSetting"),
          // hidden: this.category != 1,
          handle: () => {
            this.appSetting(row.id,row);
          }
        });
        operatingCols.push({
          type: "icon",
          icon: "ios-apps",
          text: this.$t("module.appManage.appConfig"),
          handle: () => {
            this.appConfig(row);
          }
        });
        operatingCols.push({
          type: "icon",
          icon: "ios-trash",
          text: this.$t("common.delete"),
          hidden: row.enabled == 1 ? true : false,
          handle: () => {
            this.deleted(row);
          }
        });
      } else {
        operatingCols.push({
          type: "icon",
          icon: "ios-eye",
          text: this.$t("common.detail"),
          // hidden: this.category == 1,
          handle: () => {
            this.detail(row.id);
          }
        });
      }

      return operatingCols;
    },
    async initData() {
      //   userCenter mixins
      let userCenterList = await this.getUserCenterListData();

      this.search();
    },
    getIndex(index) {
      let num = this.$refs.appTable.currentPage < 1 ? 1 : this.$refs.appTable.currentPage;
      return (num - 1) * this.$refs.appTable.param.pageSize + index + 1;
    },
    getUserCenterName(id) {
      return this.userRepositorys[id] || id;
    },
    search(page = 1) {
      // this.$refs["appTable"].load(Object.assign({}, this.formSearch), page);
      let searchParams = Object.assign({}, this.formSearch);

      if(this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.formSearch.searchType == item.key) {
            searchParams[item.key] = this.formSearch.searchTypeValue
          } else {
            searchParams[item.key] = ''
          }
        })
      }
      delete searchParams.searchType
      delete searchParams.searchTypeValue

      if (searchParams.tenantCode == "ALL") {
        searchParams.tenantCode = null;
      }
      if (searchParams.enabled == "ALL") {
        searchParams.enabled = null;
      }
      this.$refs["appTable"].load(searchParams, page);
    },
    edit(id,row) {
      new this.$pageModal(
        ApplicationEdit,
        {
          props: {
            appInfo: {
              id: id
            },
            tenantName: this.currTenantName,
            row
            // tenantName: this.$store.state[CoreModuleName].userInfo.tenantCode
          }
        },
        data => {
          this.getselectorList()
          if (data) {
            this.search(this.$refs.appTable.param.pageNum);
            this.$store.commit(CoreModuleName + "/clearAllCache");
          }
        }
      );
    },
    appSetting(id,row) {
      new this.$pageModal(
        AppSetting,
        {
          props: {
            appInfo: {
              id:id,
              clientId: row.clientId,
              tenantCode: row.tenantCode
            },
            tenantName: this.currTenantName,
            row
            // tenantName: this.$store.state[CoreModuleName].userInfo.tenantCode
          }
        },
        data => {
          this.getselectorList()
          if (data) {
            this.search(this.$refs.appTable.param.pageNum);
            this.$store.commit(CoreModuleName + "/clearAllCache");
          }
        }
      );
    },
    // 应用配置弹框
    appConfig (row) {
      new this.$pageModal(
        appConfig,
        {
          props: {
            appInfo: {
              id: row.id,
              clientId: row.clientId,
              tenantCode: row.tenantCode
            },
            row
          }
        },
        data => {
          // this.getselectorList()
          if (data) {
            this.search(this.$refs.appTable.param.pageNum);
            this.$store.commit(CoreModuleName + "/clearAllCache");
          }
        }
      );
    },
    detail(id) {
      new this.$pageModal(
        ApplicationEdit,
        {
          props: {
            appInfo: {
              id: id
            },
            tenantName: this.currTenantName,
            readOnly: true
            // tenantName: this.$store.state[CoreModuleName].userInfo.tenantCode
          }
        },
        data => {}
      );
    },
    deleted(row) {
      // // deleteAppFlag:1-可以删除应用（应用没有分配给任何租户）；0-不能删除应用（应用已关联租户）
      // if (row.deleteAppFlag == 0 && row.enabled == 0) {
      //   this.$message.error({
      //     content: this.$t("module.appManage.warning.deleteError"),
      //     duration: 3
      //   });
      //   return;
      // }
      if (row.enabled == 1) {
        this.$message.error({
          content: this.$t("module.appManage.warning.deleteError"),
          duration: 3
        });
        return;
      }
      // 删除提示级别：严重
      new $confirm(this.$t("module.appManage.warning.confirmToDelete"), this).then(() => {
        deletApp(row.id).then(() => {
          this.$message.success({
            content: this.$t("common.deleteSuccess"),
            duration: 3
          });
          this.search();
        });
      });
    },
    formReset() {
      this.$refs["roleFormSearch"].resetFields();
      this.search();
    }
  },
  watch: {
    'formSearch.searchType' : {
      handler() {
        let selectItem = this.searchTypeList.find(item => item.key == this.formSearch.searchType)
        this.searchTypePlaceholder =  selectItem ? selectItem.placeholder : ''
      }
    }
  }
};
</script>
<style lang="less">
// ok注释的样式
.ApplicationList-page {
  .ivu-form-item {
    .ivu-form-item-label {
      line-height: 14px !important;
    }
  }
}
</style>
<style lang="less">
// .ApplicationList-page {
//   .core-modal {
//     width: 774px!important;
//   }
// }
</style>
